#include "waitingpage.h"
#include "ui_waitingpage.h"
#include "../control/mainwindowcontroller.h"
#include "viewglobal.h"
#include <QTimer>
#include <QMovie>
#include <QPainter>
#include <QPen>
#include "gifwidget.h"
#include <ctime>

#define LOADING_TIME    (5)

WaitingPage::WaitingPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WaitingPage)
{
    ui->setupUi(this);

    m_gif = new GifWidget(this);
    QList<QString> files;
    files.clear();
    files << ":/img/gif1.png" << ":/img/gif2.png"
          << ":/img/gif3.png" << ":/img/gif4.png";
    m_gif->setFiles(files);
    m_gif->setDuration(2000);

    ui->gif_layout->addWidget(m_gif);

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),this,SLOT(nextPage()));

    this->setAttribute(Qt::WA_ShowModal);
    this->setWindowModality(Qt::ApplicationModal);
    this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    this->setAttribute(Qt::WA_TranslucentBackground, true);
}

WaitingPage::~WaitingPage()
{
    delete ui;
}

void WaitingPage::showEvent(QShowEvent *e)
{
    qsrand(time(NULL));
    int n = qrand() % (LOADING_TIME);
    QWidget::showEvent(e);
    timer->start(n*1000);
}

void WaitingPage::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);

    QPainter painter(this);
    QPen pen;
    pen.setColor(QColor(1, 1, 9, 128));
    painter.setPen(pen);
    painter.setBrush(QBrush(QColor(1, 1, 9, 128)));
    painter.drawRect(this->rect());
}

void WaitingPage::nextPage()
{
    timer->stop();
    MainWindowController::instance().changeTopPage(OSD::ViewGlobal::TOP_PAGE_MEET_CONTROL);
}
